//
//  HomPageSearchResultViewController.m
//  Taste
//
//  Created by 徐昊 on 16/9/23.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "HomPageSearchResultViewController.h"
#import "HomePageSearchResultTableViewCell.h"
#import "HomePageSearchResturantTableViewCell.h"
#import "HomePageSearchPersonTableViewCell.h"
#import "ZWYNetTool.h"
#import "UIImageView+WebCache.h"
#import "NSString+Vali.h"
#import "HomePageSearchResultModel.h"
#import "HomePageSearchResultRes.h"
#import "HomePageSearchResultContent.h"
#import "PersonViewController.h"
#import "HomePageDetailViewController.h"
#import "MasterCookBookViewController.h"
#import "RestaurantDetailViewController.h"
#import "OptionCollectionViewCell.h"


#define kHomePageSearchResultTableViewCellName @"HomePageSearchResultTableViewCellNameReuse"
#define kHomePageSearchResturantTableViewCellName @"HomePageSearchResturantTableViewCellNameReuse"
#define kHomePageSearchPersonTableViewCellName @"HomePageSearchPersonTableViewCellNameReuse"
#define kHomePageSearchCollectionViewCellName @"HomePageSearchCollectionViewCellNameReuse"
@interface HomPageSearchResultViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (nonatomic, assign) NSInteger *pageNum;
@property (nonatomic, strong) HomePageSearchResultModel *model;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UIView *optionView;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSArray *arrayOfName;
@property (nonatomic, strong) NSArray *arrayOfImage;

@end

@implementation HomPageSearchResultViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setup];
    NSString *searchString = [_searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *bodyString = [NSString stringWithFormat:@"cid=%ld&flag=%@&keyword=%@&page=1&pageSize=20", _cid, _flag, searchString];
    NSString *bodyLength = [NSString stringWithFormat:@"%ld", [bodyString length]];
    NSDictionary *dic = @{@"version" : @"2.50",
                          @"Content-Type" : @"application/x-www-form-urlencoded",
                          @"Content-Length" : bodyLength};
    [ZWYNetTool POST:@"http://app.legendzest.cn/m/c/searchv25" andBody:bodyString andBodyStyle:ZWYBodyString andHeader:dic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _model = [HomePageSearchResultModel modelWithDic:result];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    
    if (_cid == 0) {
        _label.text = @"全部";
    } else if (_cid == 1) {
        _label.text = @"每日资讯";
    } else if (_cid == 15) {
        _label.text = @"大师菜谱";
    } else if (_cid == 14) {
        _label.text = @"精选餐厅";
    } else if (_cid == 16) {
        _label.text = @"人物志";
    } else {
        _label.text = @"用户";
    }
    
    [_tableView registerNib:[UINib nibWithNibName:@"HomePageSearchResultTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kHomePageSearchResultTableViewCellName];
    [_tableView registerNib:[UINib nibWithNibName:@"HomePageSearchResturantTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kHomePageSearchResturantTableViewCellName];
    [_tableView registerNib:[UINib nibWithNibName:@"HomePageSearchPersonTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kHomePageSearchPersonTableViewCellName];
    _searchView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [_searchView addGestureRecognizer:tap];
    _layout.minimumInteritemSpacing = 0;
    _layout.minimumLineSpacing = 0;
    _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _collectionView.scrollEnabled = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerNib:[UINib nibWithNibName:@"OptionCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:kHomePageSearchCollectionViewCellName];
    _collectionView.layer.masksToBounds = YES;
    _collectionView.layer.cornerRadius = 15;
}
- (void)setup {
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _textField.delegate = self;
    _backView.layer.masksToBounds = YES;
    _backView.layer.cornerRadius = 5;
    _backView.layer.borderColor = [UIColor grayColor].CGColor;
    _backView.layer.borderWidth = 0.5;
    _searchView.layer.borderColor = [UIColor grayColor].CGColor;
    _searchView.layer.borderWidth = 0.5;
    _arrayOfName = @[@"全部", @"每日资讯", @"精选餐厅", @"大师菜谱", @"人物志", @"用户"];
    _arrayOfImage = @[@"ImgLib_PopView_Icon_All", @"ImgLib_PopView_Icon_DailyInformation", @"ImgLib_PopView_Icon_Restaurant", @"ImgLib_PopView_Icon_Cookbook", @"ImgLib_PopView_Icon_Master", @"ImgLib_PopView_Icon_ShowField"];
    _textField.returnKeyType = UIReturnKeySearch;
    _textField.enablesReturnKeyAutomatically = YES;
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.text = _searchString;
    _optionView.alpha = 0;
}

- (IBAction)pop:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)tap {
    if (_optionView.alpha == 1) {
        _optionView.alpha = 0;
    } else {
        _optionView.alpha = 1;
    }
}
#pragma mark - tableView协议
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_model.res[indexPath.section].cid == 2) {
        return 60;
    } else {
        return 100;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _model.res[section].content.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _model.res.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (_model.res[section].cid == 1) {
        return @"每日资讯";
    } else if (_model.res[section].cid == 14) {
        return @"大师菜谱";
    } else if (_model.res[section].cid == 15) {
        return @"精选餐厅";
    } else if (_model.res[section].cid == 16){
        return @"人物志";
    } else {
        return @"味觉大师用户";
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_model.res[indexPath.section].cid == 15) {
        HomePageSearchResturantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kHomePageSearchResturantTableViewCellName];
        cell.searchString = _searchString;
        cell.content = _model.res[indexPath.section].content[indexPath.row];
        return cell;
    } else if (_model.res[indexPath.section].cid == 2) {
        HomePageSearchPersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kHomePageSearchPersonTableViewCellName];
        cell.content = _model.res[indexPath.section].content[indexPath.row];
        return cell;
    } else {
        HomePageSearchResultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kHomePageSearchResultTableViewCellName];
        cell.searchString = _searchString;
        cell.cid = _model.res[indexPath.section].cid;
        cell.content = _model.res[indexPath.section].content[indexPath.row];
        cell.searchString = _searchString;
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_model.res[indexPath.section].cid == 15) {
        RestaurantDetailViewController *vc = [[RestaurantDetailViewController alloc] init];
        vc.numString = _model.res[indexPath.section].content[indexPath.row].HomePageSearchResultContent_id;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (_model.res[indexPath.section].cid == 16) {
        PersonViewController *vc = [[PersonViewController alloc] init];
        vc.numString = _model.res[indexPath.section].content[indexPath.row].HomePageSearchResultContent_id;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (_model.res[indexPath.section].cid == 1) {
        HomePageDetailViewController *vc = [[HomePageDetailViewController alloc] init];
        vc.numString = _model.res[indexPath.section].content[indexPath.row].HomePageSearchResultContent_id;
        NSLog(@"%@", _model.res[indexPath.section].content[indexPath.row].HomePageSearchResultContent_id);
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (_model.res[indexPath.section].cid == 14) {
        MasterCookBookViewController *vc = [[MasterCookBookViewController alloc] init];
        vc.numString = _model.res[indexPath.section].content[indexPath.row].HomePageSearchResultContent_id;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
#pragma mark - textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self resignTextResponder];
    if (textField.returnKeyType == UIReturnKeySearch) {
        if ([_textField.text length] > 0) {
            self.flag = @"1";
            self.searchString = self.textField.text;
            [self request];
        }
    }
    return YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self resignTextResponder];
}

- (void)resignTextResponder {
    if ([_textField isFirstResponder])
    {
        [_textField resignFirstResponder];
    }
}

#pragma mark - collectionView协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    OptionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kHomePageSearchCollectionViewCellName forIndexPath:indexPath];
    cell.label.text = _arrayOfName[indexPath.row];
    NSString *string = _arrayOfImage[indexPath.row];
    cell.pic.image = [UIImage imageNamed:string];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    _layout.itemSize = CGSizeMake(_optionView.bounds.size.width, _optionView.bounds.size.height / 6);
    return _layout.itemSize;
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    _optionView.alpha = 0;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    _label.text = _arrayOfName[indexPath.row];
    _optionView.alpha = 0;
    if (indexPath.row == 0) {
        _cid = 0;
    } else if (indexPath.row == 1) {
        _cid = 1;
    } else if (indexPath.row == 2) {
        _cid = 15;
    } else if (indexPath.row == 3) {
        _cid = 14;
    } else if (indexPath.row == 4) {
        _cid = 16;
    } else if (indexPath.row == 5) {
        _cid = 2;
    }
    [self request];
    
}
- (void)request {
    NSString *searchString = [_searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *bodyString = [NSString stringWithFormat:@"cid=%ld&flag=%@&keyword=%@&page=1&pageSize=20", _cid, _flag, searchString];
    NSString *bodyLength = [NSString stringWithFormat:@"%ld", [bodyString length]];
    NSDictionary *dic = @{@"version" : @"2.50",
                          @"Content-Type" : @"application/x-www-form-urlencoded",
                          @"Content-Length" : bodyLength};
    [ZWYNetTool POST:@"http://app.legendzest.cn/m/c/searchv25" andBody:bodyString andBodyStyle:ZWYBodyString andHeader:dic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _model = [HomePageSearchResultModel modelWithDic:result];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
